package org.example;

import org.example.http.BRequest;
import org.example.http.BResponse;
import org.example.http.BServlet;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author lilei
 * @date 2020-04-06
 */
public class BTomcat {
    private static final int PORT = 8080;
    private static Map<String, BServlet> servletMapping = new HashMap<>();
    private static String WEB_URL = "web.properties";


    //    J2EE 标准
    //    Servlet
    //    Request
    //    Response
    //     1、配置到启动端口，默认8080  ServerSocket IP：localhost
    //     2、配置web.xml 自己写的Servlet继承HttpServlet
    //    servlet-name
    //    servlet-class
    //    url-pattern
    //     3、读取配置，url-pattern   和   Servlet 建立一个映射关系
    //    Map servletMapping

    // 初始化配置和映射关系
    public void init() {
        try {
            FileInputStream fileInputStream = new FileInputStream(this.getClass().getResource("/").getPath() + WEB_URL);
            Properties properties = new Properties();
            properties.load(fileInputStream);
            for (Object k : properties.keySet()) {
                String key = k.toString();
                if (key.endsWith(".url")) {
                    // 取出url前面的前缀  servlet.one.
                    String prefixKey = key.replaceAll("\\.url$", "");
                    String url = properties.getProperty(key);
                    String className = properties.getProperty(prefixKey + ".className");
                    BServlet obj = (BServlet) Class.forName(className).newInstance();
                    servletMapping.put(url, obj);
                }
            }


        } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    // 启动
    public void start() {
        init();

        try {

            ServerSocket server = new ServerSocket(this.PORT);
            System.out.println("B Tomcat 已启动，监听的端口是：" + this.PORT);

            while (true) {
                Socket client = server.accept();
                process(client);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void process(Socket client) throws IOException {
        InputStream in = client.getInputStream();
        OutputStream out = client.getOutputStream();
        BRequest request = new BRequest(in);
        BResponse response = new BResponse(out);

        String url = request.getUrl();
        if (servletMapping.containsKey(url)) {
            servletMapping.get(url).service(request, response);
        } else {
            response.write("404 - Not Found");
        }
        out.flush();
        out.close();
        in.close();
        client.close();
    }

    public static void main(String[] args) {
        new BTomcat().start();
    }


//     4、HTTP 请求，发送的数据就是字符串，有规律的字符串（HTTP协议）
//     5、从协议内容中拿到 URL，把相应的 Servlet 用反射进行实例化
//     6、调用实例化对象的 service() 方法，执行具体的逻辑 doGet/doPost 放啊
//     7、Request（InputStream）/Response（OutputStream）
}